package com.company.test.antibrush.handler;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;


@Component
public class AntiBrushInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断请求是否属于方法的请求
        if(handler instanceof HandlerMethod){

            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法中的注解,看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean login = accessLimit.needLogin();

            String userid =  "";

            //如果需要登录
            if(!login){
                render(response,"用户未登录!!!");
                return false;
            }

            userid ="1";
            if (userid.length()<1){
                //获取登录的session进行判断;
                render(response,"未获取用户登录信息!!!");
                return false;
            }
            String ip = request.getLocalAddr();
            String url = request.getRequestURL().toString();
            final String key = "req_".concat(ip).concat("_").concat(userid).concat("_").concat(url);
            //从redis中获取用户URL访问的次数
            String scount = redisTemplate.opsForValue().get(key);
            if(scount == null){
                //第一次访问
                redisTemplate.opsForValue().set(key,"1",seconds, TimeUnit.SECONDS);
            }else{
                Integer count = Integer.parseInt(scount);
                if(count < maxCount){
                    //加1
                    redisTemplate.opsForValue().set(key,(count+1)+"",seconds, TimeUnit.SECONDS);
                }else{
                    //超出访问次数
                    render(response,"访问次数过于频繁"); //这里的CodeMsg是一个返回参数
//                    throw new RRException("访问次数过于频繁");
                    return false;
                }
            }
        }

        return true;
    }
    private void render(HttpServletResponse response, String cm)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JSON.toJSONString(cm);
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}

